class SharingController < ApplicationController
  before_filter :login_required
  layout "main"
  model :invitation 
  
  def index
    @current = "sharing"
    @page_title = "Sharing"
    
    user = User.find(@session[:user].id)

    #acceptors = user.acceptors.find(:all, :select => "relationships.validated, users.*")
    #initiators = user.initiators.find(:all, :select => "relationships.validated, users.*")
    
    #relationships = []

    # get initiated relationships
    #unless acceptors.length == 0
    #  relationships = acceptors
    #end

    # get accepted relationships
    #unless initiators.length == 0 
    #  relationships << initiators
    #end
    
    dummy = []
    @partners = user.partners
    
    @invitations = user.sent_invitations
    
    @pending_invitations = user.pending_invitations
    
    message = "#{@invitations.count} #{@pending_invitations.count}"
   # partners.each do |partner|
    #  message << "#{partner.first_name}  #{partner.last_name}<br/>" 
    #end
    
    flash[:notice] = "#{message}"
    
    
    #@relationship_pages, @relationships = paginate_collection partners, :page => @params[:page], :per_page => 100

  end

  def invite    
    @current = "sharing"
    @page_title = "Sharing Request"

    @success = []
    @message = []
    
    if request.post? && @params[:sharing][:invitees] != ""
      @invitees =  @params[:sharing][:invitees].split(/[\r\n]/) 

        @invitees.each do |invitee|
          
          @invited = User.find(:all,
                               :select => "users.*",
                               :joins => "LEFT JOIN relationships ON (users.id = relationships.acceptor AND relationships.initiator = #{@session[:user].id}) OR (users.id = relationships.initiator AND relationships.acceptor = #{@session[:user].id})",
                               :conditions => ["(users.login = ? OR users.email = ?) AND relationships.initiator IS NULL AND relationships.acceptor IS NULL", invitee, invitee])
          
          if @invited
            @invited.each do |invite|
                @relationship = Relationship.new
                @relationship.initiator = @session[:user].id
                @relationship.acceptor = invite.id
                @relationship.security_token = Digest::MD5.hexdigest("salt-#{Clock.now}-#{invite.id}")[0..39]
                @relationship.save
                @success << "#{invite.first_name} #{invite.last_name}"
                url = url_for(:action => 'accept')
                url += "?key=#{@relationship.security_token}"
                email = SharingMailer.create_request(@session[:user],invite, url)
                email.set_content_type("text/html")
                SharingMailer.deliver(email)
            end 
            
          end
          
        end # @invitees loop
        
      if !@success.empty?
        @message << l("Sharing Reqest emails have been sent to #{@success.join(', ')}.")
      end

      redirect_to :controller => "sharing"
    else # request.post check else
    
      @message << "You are already sharing with the requested user, have a pending share request, or you have entered an invalid Login IDs or Email Addresses. Please try again."

    end # request.post check end
    
    if request.post?
    
      if !@message.empty?
        flash[:notice] = "#{@message.join('<br/>')}"
      end
    
    else
    
      flash[:notice] = nil
    end
    
  end
  
  def resend
  
    @invited = User.find(:all,
                       :select => "users.*, relationships.security_token",
                       :joins => "JOIN relationships ON users.id = relationships.acceptor AND relationships.initiator = #{@session[:user].id}",
                       :conditions => ["relationships.id = ?", @params[:id]])
                       
    if @invited
      @invited.each do |invite|
          flash[:notice] = l("Sharing Reqest email has been resent to #{invite.first_name} #{invite.last_name}.")
          url = url_for(:action => 'accept')
          url += "?key=#{invite.security_token}"
          email = SharingMailer.create_request(@session[:user], invite, url)
          email.set_content_type("text/html")
          SharingMailer.deliver(email)
      end 
    else
      flash[:notice] = l("You are trying to resend a non-existing Sharing Request. Please check your URL and try again or create a new Sharing Request.")    
    end
    redirect_to :controller => "sharing"      
  end

  def accept
    @relationship = Relationship.find_by_security_token(@params[:key], :conditions => "validated = 0 AND acceptor = #{@session[:user].id}")
    
    if @relationship
      @inviter = User.find_by_id(@relationship.initiator)
  
      if @relationship.update_attribute(:validated, 1)
        flash[:notice] = "#{@inviter.first_name} #{@inviter.last_name}'s Share Request has been validated. You can now share stories with #{@inviter.first_name} #{@inviter.last_name}."
      end
      
    else
      flash[:notice] = "Unable to find Share Request. Please make sure that the link you used is valid or send an invite to the other user yourself."
    end
    
    redirect_to :controller => "sharing"
    
  end

  def delete
    @user = User.find_by_id(@session[:user].id)
    
    @relationship = Relationship.find_by_id(@params[:id], :conditions => ["initiator = ? OR acceptor = ?",@session[:user].id, @session[:user].id])
    @relationship.destroy
    
    flash[:notice] = "Sharing with #{@user.first_name} #{@user.last_name} has been disabled."
    redirect_to :controller => "sharing"
  end
  
  def share_story
    @current = "sharing"
    user = User.find_by_id(@session[:user].id)
    
    # this is ugly, needs to be cleaned up
    @borrowers = User.find(:all,
                           :select => "users.id AS user_id, users.login, users.email, users.first_name, users.last_name",
                           :joins => "JOIN relationships ON (users.id = relationships.initiator AND relationships.acceptor = #{@session[:user].id}) OR (users.id = relationships.acceptor AND relationships.initiator = #{@session[:user].id})",
                           :conditions => "relationships.validated = 1 AND users.id <> #{@session[:user].id}",
                           :order => "users.last_name")
                           
    @story_id = params[:story_id]
    @story = user.stories.find(params[:id])
    
    @page_title = "Select users that you would like to share '#{@story.title}' with:"
    
    sharedstories = SharedStory.find_all_by_story_id(params[:id], :conditions => ["owner_id = ?", @session[:user].id])
    
    @sharedstories = Array.new
    for element in sharedstories
      @sharedstories << element.borrower_id
    end
    
    if request.post?
    
      if params[:user_ids] then
      
        SharedStory.delete_all(["story_id = ? AND owner_id = ?",params[:id], @session[:user].id])
        
        for user_id in params[:user_ids].uniq
            sharedstory = SharedStory.new
            sharedstory.owner_id = @session[:user].id
            sharedstory.borrower_id = user_id
            sharedstory.story_id = params[:id]
            sharedstory.save
        end
        
      else
        SharedStory.delete_all(["story_id = ? AND owner_id = ?",params[:id], @session[:user].id])
      end  
      
      flash[:notice] ="'#{@story.title}' sharing updated"
      redirect_to :controller => 'story', :action => 'view', :id => params[:id]
          
    end 
  end
end

